<style lang="less">
    @import './index.less';
</style>

<template>
<div>
  <Card dis-hover>
    <Row v-show="searchRow" class="margin-bottom-5">
      <i-col span="20" >
        <Input placeholder="合同编号" v-model="searchInfo.contract_number" size="small" style="width: 200px"></Input>
        <Button class="margin-right-5" type="primary" size="small" icon="ios-search" @click="search">搜索</Button>
        <Button type="primary" size="small" icon="arrow-down-b" @click="moreSearch">高级搜索</Button>
      </i-col>
      <i-col span="4">
        <addBtn @addclick="addHandle" class="pull-right"></addBtn>
      </i-col>
    </Row>
    <Row v-show="!searchRow" class="margin-bottom-5">
      <i-col span="20">
        <Input placeholder="合同编号" v-model="searchInfo.contract_number" size="small" style="width: 200px"></Input>
        <Select placeholder="客户名称" v-model="searchInfo.customer_id" transfer clearable filterable style="width: 200px"  size="small">
          <Option v-for="item in companyList" :key="item.contract_id" :value="item.customer_id">{{item.customer_name}}</Option>
        </Select>
        <Select placeholder="合同状态" v-model="searchInfo.status" transfer clearable  style="width: 200px"  size="small">
          <Option v-for="(item,index) in indexData.contractStatus" :key="item.index" :value="item.value">{{item.label}}</Option>
        </Select>
        <Button class="margin-right-5" type="primary" size="small" icon="ios-search" @click="search">搜索</Button>
        <Button type="primary" size="small" @click="moreSearch" icon="arrow-up-b">收起</Button>     
      </i-col>
      <i-col span="4">
        <addBtn @addclick="addHandle" class="pull-right"></addBtn>
      </i-col>
    </Row>
    <Modal width="1100" :loading="loading" v-model="modalControl" :title="modalTitle" @on-cancel="cancel('modalRef')">
      <Form :model="modalForm" ref="modalRef" :rules="ruleValidate" label-position="right" :label-width="100">
        <div class="division-tips">
          <Button type="text" icon="arrow-up-b" v-show="baseInfo" @click="baseInfo = !baseInfo"></Button>
          <Button type="text" icon="arrow-down-b" v-show="!baseInfo" @click="baseInfo = !baseInfo"></Button>
          <span>基本信息</span>
        </div>
        <div v-show="baseInfo">
          <Row :gutter="15">
            <i-col span="10" offset="1">
              <FormItem label="客户名称" prop="customer_id">
                <Select v-model="modalForm.customer_id" transfer>
                  <Option v-for="item in companyList" :key="item.contract_id" :value="item.customer_id">{{item.customer_name}}</Option>
                </Select>
              </FormItem>
            </i-col>
            <i-col span="10" offset="1">
              <FormItem label="合同负责人" prop="responsible">
                <Select v-model="modalForm.responsible" transfer filterable>
                  <Option v-for="item in employeeList" :key="item.responsible" :value="item.responsible">{{item.employee_name}}</Option>
                </Select>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="15">
            <i-col span="10" offset="1">
              <FormItem label="合同名称" prop="contract_name">
                <Input type="text" v-model="modalForm.contract_name"></Input>
              </FormItem>
            </i-col>
            <i-col span="10" offset="1">
              <FormItem label="合同类型">
                <Select v-model="modalForm.type">
                  <Option value="收入">收入</Option>
                </Select>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="15">
            <i-col span="10" offset="1">
              <FormItem label="合同开始时间" prop="contract_start_date">
                <DatePicker type="date" ref="contractStart" transfer placement="bottom-start" v-model="modalForm.contract_start_date"></DatePicker>
              </FormItem>
            </i-col>
            <i-col span="10" offset="1">
              <FormItem label="合同结束时间" prop="contract_end_date">
                <DatePicker type="date" ref="contractEnd" transfer placement="bottom-start" v-model="modalForm.contract_end_date"></DatePicker>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="15">
            <i-col span="10"  offset="1">
              <FormItem label="合同申请日期">
                <DatePicker type="date" ref="contractSign" v-model="modalForm.contract_date" transfer placement="bottom-start" disabled></DatePicker>            
              </FormItem>
            </i-col>
            <i-col span="10" offset="1">
              <FormItem label="备注">
                <Input type="textarea" v-model="modalForm.remark"></Input>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="15">
            <i-col span="10" offset="1">
              <FormItem label="合同附件">
                <Upload 
                    ref="CreateUpload"
                    name="file"
                    :headers="{Authorization: 'Bearer' + token}"
                    :action=" this.util.ajaxUrl.file +'/sys/files '"
                    :on-success="handleFileSuccess"
                    :on-remove="removeFile">
                    <Button type="ghost" icon="ios-cloud-upload-outline">选择上传的合同附件</Button>
                  </Upload>
              </FormItem>
            </i-col>
          </Row>
        </div>
        <div class="division-tips">
          <Button type="text" icon="arrow-up-b" v-show="prodInfo" @click="prodInfo = !prodInfo"></Button>
          <Button type="text" icon="arrow-down-b" v-show="!prodInfo" @click="prodInfo = !prodInfo"></Button>
          <span>产品信息</span>
        </div>
        <div v-show="prodInfo">
           <div v-for="(item,index) in modalForm.sales" :key="index" class="dotted-box">
              <Row :gutter="15">
                <i-col span="16" offset="1">
                  <FormItem label="产品名称" :prop="'sales.' + index + '.product_id'" :rules="{required: true, message: '请选择产品', trigger: 'change'}">
                    <Select transfer v-model="item.product_id" @on-change="(id) => getProductInfo(id,index)">
                      <Option v-for="item in productList" :key="item.product_id" :value="item.product_id">{{item.product_name}}</Option>
                    </Select>
                  </FormItem>
                </i-col>
              </Row>
              <Row>
                <i-col span="5" offset="1">
                  <FormItem label="单价:" :label-width="50">
                    <span>{{item.price}} 元</span>
                  </FormItem>
                </i-col>
                <i-col span="5">
                  <FormItem label="数量:" :label-width="50">
                    <Button type="text" icon="minus-round" class="margin-right-10" @click="sub(item,index)"></Button>
                    <strong >{{item.quantity}}</strong>
                    <Button type="text" icon="plus-round" class="margin-left-10" @click="add(item,index)"></Button>
                  </FormItem>
                </i-col>
                <i-col span="5">
                  <FormItem label="总价:" :label-width="50">
                    <span>{{item.totalSum}} 元</span>
                  </FormItem>
                </i-col>
                <i-col span="5">
                  <FormItem label="优惠价:" :label-width="70" 
                    :prop="'sales.' + index + '.amount'" 
                    :rules="[{required: true, message: '请填写优惠金额', trigger: 'blur'},{ validator: valideNumber , trigger: 'change'}]">
                    <Input type="text" size="small" style="width:89%"  v-model="item.amount" @on-change="changeSum"></Input>
                    <span>元</span>
                  </FormItem>
                </i-col>
                <i-col span="2" pull="1">
                  <FormItem>
                    <Button type="text" icon="trash-a" v-show="index !== 0" @click="removeSales(index)"></Button>
                  </FormItem>
                </i-col>
              </Row>
            </div>
            <Row>
              <i-col span="4" offset="4">
                  <Button type="dashed" icon="plus" @click="addSales">添加更多产品信息</Button>
              </i-col>
            </Row>
            <Row>
              <i-col span="5" offset="17">
                <span>合同金额: <strong style="font-size:16px">{{sum}}</strong> 元</span>
              </i-col>
            </Row>
        </div>
        <div class="division-tips margin-top-10">
          <Button type="text" icon="arrow-up-b" v-show="planInfo" @click="planInfo = !planInfo"></Button>
          <Button type="text" icon="arrow-down-b" v-show="!planInfo" @click="planInfo = !planInfo"></Button>
          <span>应收周期</span>
        </div>
        <div v-show="planInfo">
          <Row v-for="(item,index) in modalForm.receivables" :key="index" type="flex" justify="space-around">
            <i-col span="7">
              <FormItem label="应收期次" 
                :prop="'receivables.' + index + '.count'" 
                :rules="{required: true, message: '请填写应收期次', trigger: 'blur'}">
                <Input  v-model="item.count" disabled></Input>
              </FormItem>
            </i-col>
            <i-col span="7">
              <FormItem label="应收约定回款时间" 
                :prop="'receivables.' + index + '.receivable_date'" 
                :rules="{type:'date', required: true, message: '请填写应收约定回款时间', trigger: 'blur'}">
                <DatePicker type="date" ref="receivableDate" placement="top-start" transfer v-model="item.receivable_date"></DatePicker>
              </FormItem>
            </i-col>
            <i-col span="7">
              <FormItem label="应收金额" 
                :prop="'receivables.' + index + '.receivable_amount'" 
                :rules="[{required: true, message: '请填写应收金额', trigger: 'blur'},{ validator: valideNumber , trigger: 'change'}]">
                <Input v-model="item.receivable_amount" style="width:90%"  @on-change="changeReceivableMoney"></Input>
                <span>元</span>                     
              </FormItem>
            </i-col>
            <i-col span="1" pull="2">
              <FormItem>
                <Button type="text" icon="trash-a" v-show="index !== 0" @click="removeReceivalbe(index)"></Button>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col span="4" offset="4">
                <Button type="dashed" icon="plus" @click="addReceivalbe()">添加应收周期</Button>
            </i-col>
          </Row>
          <Row>
            <i-col span="5" push="17">
                <span>总应收金额: <strong style="font-size:16px">{{receivableSum}}</strong> 元</span>
                <div v-show="receivableSum !== sum" class="error-message">应收总额应与合同总金额相等</div>
            </i-col>
          </Row>
        </div>
      </Form>
      <div slot="footer">
          <Button type="ghost" size="large" @click="save('modalRef')">保存</Button>
          <Button type="primary" size="large"  @click="check('modalRef')" :loading="btnLoading">提交审核</Button>
      </div>
    </Modal>
    <Table :columns="contractColumns" :data="contractData.data"></Table>
    <Page :current="currentPage" :total="contractData.totalCount" :page-size="pageSize" show-total @on-change="changepage"></Page>
  </Card>
</div>
</template>

<script>
import moment from 'moment';
import deleteBtn from './component/access-delete-button.vue';
import checkBtn from './component/access-check-button.vue';
import modifyBtn from './component/access-modify-button.vue';
import addBtn from './component/access-add-button.vue';
import uploadBtn from './component/access-upload-button.vue';
import util from '@/libs/util'
import indexData from './indexData.js'


export default {
  data() {
    var valideNumber = (rule, value, callback) => {
        if(!Number.isInteger(+value)) {
           callback(new Error('请输入数字值'));
        }else {
          callback()
        }
    };
    return{
      indexData:[],
      index:1,
      util:util,
      valideNumber:valideNumber,
      searchRow:true,
      searchInfo:{
        contract_number:'',
        customer_id:'',
        status:''
      },
      contract_id:'',
      pageSize:15,
      currentPage:1,
      sum:0,
      receivableSum:0,
      contractData:[],
      companyList:[],
      flow:[],
      checkForm:[],
      employeeList:[],
      productList:[],
      loading:true,
      btnLoading:false,
      modalControl:false,
      baseInfo:true,
      prodInfo:true,
      planInfo:true,
      modalTitle:'',
      modalForm:{
        contract_date:new Date(),
        sales:[{quantity:1,price:0}],
        receivables:[{index:1,count:'01/01'}],
      },
      ruleValidate: {
        customer_id:[
           { required: true, message: '请选择客户', trigger: 'blur' }
        ],
        responsible:[
           { required: true, message: '请选择合同负责人', trigger: 'blur' }
        ],
        contract_start_date:[
           { type:'date', required: true, message: '请填写合同开始时间', trigger: 'blur' }
        ],
        contract_end_date:[
           { type:'date', required: true, message: '请填写合同结束时间', trigger: 'blur' }
        ],
        contract_name:[
          { required: true, message: '请输入合同名称', trigger: 'blur' }
        ]
      },
      contractColumns:[
        {
          title:'合同编号',
          key:'contract_number',
          align:'center',
          render:(h,params) => {
            if(params.row.contract_number) {
              return h('span',{},params.row.contract_number)
            }else {
              return h('span',{},'暂无合同编号')
            }
          }
        },
        {
          title:'合同名称',
          key:'contract_name',
          align:'center'
        },
        {
          title:'合同负责人',
          key:'responsible_name',
          align:'center'
        },
        {
          title:'合同申请人',
          key:'creator',
          align:'center'
        },
        {
          title:'客户名称',
          key:'customer_name',
          align:'center'
        },
        {
          title:'合同金额(元)',
          key:'contract_amount',
          align:'center'
        },
        {
          title:'合同类型',
          key:'type',
          align:'center'
        },
        {
          title:'合同申请日期',
          key:'contract_date',
          align:'center',
          render:(h,params) => {
            if(params.row.contract_date) {
              return h('span',{},moment(params.row.contract_date).format('YYYY-MM-DD'))
            }else {
              return h('span',{},'')
            }
          }
        },
        {
          title:'合同状态',
          key:'status',
          align:'center',
          render:(h,params) => {
            if(params.row.status === '未提交') {
              return h('span',{},params.row.status)
            }else if(params.row.status === '审核通过'){
              return h('Poptip', {
                  props: {
                      trigger: 'hover',
                      title: this.flow.length + '条审核记录',
                      placement: 'bottom-end'
                  }
              }, [
                  h('span', {
                    on:{
                      mouseenter:() => {
                        this.getFlow(params.row.contract_id)
                      }
                    },
                    style:{
                      color:'#19be6b' // success
                    }
                  },params.row.status),
                  h('div', {
                      slot: 'content'
                  }, [
                      h('ul', this.flow.map(item => {
                          return h('li', {
                              style: {
                                  textAlign: 'center',
                                  padding: '4px'
                              }
                          }, item.approvalDate + '：' +item.approvalUserId + item.action + ',' + '审核意见：' + item.comment);
                      })),
                      h(uploadBtn,{
                        props:{
                          status:params.row.status
                        },
                        on:{
                          uploadclick:() => {
                            this.uploadContract(params.row)
                          }
                        }
                      })
                  ])
              ]);
            }else if(params.row.status === '审核驳回') {
              return h('Poptip', {
                  props: {
                      trigger: 'hover',
                      title: this.flow.length + '条审核记录',
                      placement: 'bottom-end'
                  }
              }, [
                  h('span', {
                    on:{
                      mouseenter:() => {
                        this.getFlow(params.row.contract_id)
                      }
                    },
                    style:{
                      color:'#ed3f14' // error
                    }
                  },params.row.status),
                  h('div', {
                      slot: 'content'
                  }, [
                      h('ul', this.flow.map(item => {
                          return h('li', {
                              style: {
                                  textAlign: 'center',
                                  padding: '4px'
                              }
                          }, item.approvalDate + '：' +item.approvalUserId + item.action + ',' + '审核意见：' + item.comment);
                      }))
                  ])
              ]);
            }else {
              return h('Poptip', {
                  props: {
                      trigger: 'hover',
                      title: this.flow.length + '条审核记录',
                      placement: 'bottom-end'
                  }
              }, [
                  h('span', {
                    on:{
                      mouseenter:() => {
                        this.getFlow(params.row.contract_id)
                      }
                    },
                    style:{
                      color:'#2d8cf0' // info
                    }
                  },params.row.status),
                  h('div', {
                      slot: 'content'
                  }, [
                      h('ul', this.flow.map(item => {
                          return h('li', {
                              style: {
                                  textAlign: 'center',
                                  padding: '4px'
                              }
                          }, item.approvalDate + '：' +item.approvalUserId + item.action + ',' + '审核意见：' + item.comment);
                      }))
                  ])
              ]);
            }
          }
        },
        {
          title:'操作',
          align:'center',
          render:(h,params) => {
            // 合同申请人如果不是登陆用户，该登陆用户只能查看其在权限范围内的合同详情
            if(params.row.creator !== this.userName) {
              return h('Poptip', {
                props:{
                  trigger:'hover',
                  placement:'left',
                }
              },[
                h('Button',{
                  props:{
                    type:'text',
                    size:'small',
                    icon:'ios-color-wand',
                  }
                }),
                h('div',{
                  slot:'content',
                },[
                  h('Button',{
                    props:{
                      type:'info',
                      size:'small',
                      //icon:'qr-scanner'
                    },
                    style:{
                      marginRight:'5px',
                    }, 
                    on:{
                      click:() => {
                        this.$router.push({
                          name:'contract_my-contract-detail',
                          params:{id:params.row.contract_id,status:params.row.status,creator:params.row.creator}
                        })
                      }
                    }
                  },'详细信息')
                ])
              ])
            }else {
              return h('Poptip', {
                props:{
                  trigger:'hover',
                  placement:'left',
                }
              },[
                h('Button',{
                  props:{
                    type:'text',
                    size:'small',
                    icon:'ios-color-wand',
                  }
                }),
                h('div',{
                  slot:'content',
                },[
                  h('Button',{
                    props:{
                      type:'info',
                      size:'small',
                    },
                    style:{
                      marginRight:'5px',
                    }, 
                    on:{
                      click:() => {
                        this.$router.push({
                          name:'contract_my-contract-detail',
                          params:{id:params.row.contract_id,status:params.row.status,creator:params.row.creator}
                        })
                      }
                    }
                  },'详细信息'),
                  h(checkBtn,{
                    props:{
                      status:params.row.status
                    },
                    on: {
                      checkclick:() => {
                        this.$Modal.confirm({
                          title: '确认',
                          content: '确认要提交与【' + params.row.customer_name + '】的合同审核吗？',
                          onOk: () => {
                            this.checkHandle(params.row);
                          }
                        });
                      }
                    }
                  },'提交审核'),
                  h(modifyBtn,{
                    props:{
                      status:params.row.status
                    },
                    on: {
                      modifyClick: () => {
                        this.modifyHandle(params.row.contract_id)
                      }
                    }
                  },'修改'),
                  h(deleteBtn,{
                    props:{
                      status:params.row.status
                    },
                    on: {
                      delclick:() => {
                        this.$Modal.confirm({
                          title: '确认',
                          content: '确认要删除与【' + params.row.customer_name + '】的合同信息吗？',
                          onOk: () => {
                            this.delete(params.row.contract_id);
                          }
                        });
                      }
                    }
                  })
                ])
              ])
            }
          }
        }
      ],
    }
  },
  methods:{
    getContracts() {
      this.$http.get('/fi/contracts/page?like=&customer_id='+this.searchInfo.customer_id+'&org_id=&responsible=&status='+this.searchInfo.status+'&contract_number='+this.searchInfo.contract_number+'&pageSize='+this.pageSize+'&currentPage=' + this.currentPage).then((res) => {
        this.contractData = res.data.returnValue
      })
    },
    getCompanys() {
      this.$http.get('/customer/customers').then((res) => {
        this.companyList = res.data.returnValue
      })
    },
    getFlow(id) {
      this.$flowHttp.get('/flow/history?category=contract-approval&key=' + id).then((res) => {
        this.flow = res.data.returnValue
      })
    },
    getEmployees() {
      this.$http.get('/fi/hr/employeelist?org_id=').then((res) => {
        this.employeeList = res.data
      })
    },
    getProducts() {
      this.$http.get('/fi/sale/products').then((res) => {
        this.productList = res.data.returnValue
      })
    },
    getProductInfo(id,index) {
        id.length !== 0 ? this.modalForm.sales[index].price = this.productList[_.findIndex(this.productList,{product_id:id})].price : this.modalForm.sales[index].price = 0
        this.modalForm.sales[index].totalSum = parseFloat(this.modalForm.sales[index].price * this.modalForm.sales[index].quantity) // 当前商品价格
    },
    search() {
      this.getContracts()
    },
    moreSearch() {
      this.searchInfo.customer_id = ''
      this.searchInfo.status = ''
      this.searchInfo.contract_number = ''
      this.searchRow = !this.searchRow
      this.getContracts()
    },
    changepage(page) {
      this.currentPage = page
      this.getContracts()
    },
    handleFileSuccess(res,file,fileList) {
     if (res.success) {
        // 只能上传一个文件
        if(fileList.length !== 1) {
          fileList.splice(0,1)
        }
        this.$Message.success('文件上传成功')
        this.modalForm.oss_id = res.returnValue;
        this.modalForm.oss_name = file.name
      } else {
        this.$Message.error('文件上传失败,请重试');
      }
    },
    removeFile(file, fileList){
      this.modalForm.oss_id = '';
      this.modalForm.oss_name = ''
    },
    add(item,index) {
      item.quantity++
      this.getProductInfo(item.product_id,index)
    },
    sub(item,index) {
      item.quantity--
      if(item.quantity <= 1){
        item.quantity = 1
      }
      this.getProductInfo(item.product_id,index)
    },
    addSales() {
      this.modalForm.sales.push({quantity:1})
    },
    removeSales(index) {
      this.modalForm.sales.splice(index,1)
      this.changeSum()
    },
    changeSum() {
      var sum = 0
      _.forEach(this.modalForm.sales,item => {
        if(item.amount.length !== 0) {
          sum = sum + parseFloat(item.amount)
        }else {
          sum = sum + item.amount
        }
      })
      this.sum = parseFloat(sum)
    },
    changeReceivableMoney() {
      var sum = 0
      _.forEach(this.modalForm.receivables,item => {
        if(item.receivable_amount.length !== 0) {
          sum = sum + parseFloat(item.receivable_amount)
        }else {
          sum = sum + item.receivable_amount
        }
      })
      this.receivableSum = parseFloat(sum)
    },
    addReceivalbe() {
      this.index++
      this.modalForm.receivables.push({index:this.index})
      _.forEach(this.modalForm.receivables,item => {
        item.count = this.padLeft(item.index.toString()).toString() + '/' + this.padLeft(this.modalForm.receivables.length.toString()).toString()
        return item
      })
    },
    removeReceivalbe(index) {
      this.index--
      this.modalForm.receivables.splice(index ,1)
      for(let i= 0; i < this.modalForm.receivables.length; i++) {
        this.modalForm.receivables[i].count = this.padLeft((i + 1).toString()).toString() + '/' + this.padLeft(this.modalForm.receivables.length.toString()).toString()
      }
      this.changeReceivableMoney()
    },
    cancel(name) {
      this.modalForm = {
        contract_date:new Date(),
        sales:[{quantity:1,price:0}],
        receivables:[{index:1,count:'01/01'}],
      }
      this.receivableSum = 0
      this.sum = 0
      this.baseInfo = true,
      this.prodInfo = true,
      this.planInfo = true
      this.index = 1
      this.$refs['CreateUpload'].clearFiles()
      this.cleanParameter()
      this.cleanDatePicker()
      this.$refs[name].resetFields()
    },
    cleanDatePicker() {
      this.$refs.contractStart.handleClear()
      this.$refs.contractEnd.handleClear()
      this.$refs.contractSign.handleClear()
      this.$refs.receivableDate[0].handleClear()
    },
    cleanParameter() {
      this.receivableSum = 0
      this.sum = 0
      this.baseInfo = true,
      this.prodInfo = true,
      this.planInfo = true
    },
    reloading() {
      this.loading = false
      this.$nextTick(() => {
        this.loading = true
      })
    },
    // 将前端需要处理的数据的步骤抽象成一个方法
    handleParmas() {
      _.forEach(this.modalForm.sales,item => {
        delete item.totalSum
      })
      _.forEach(this.modalForm.receivables,item => {
        delete item.index
      })
      this.modalForm.org_id=this.employeeList[_.findIndex(this.employeeList,{responsible:this.modalForm.responsible})].org_id
      // 转换datePicker传入的UTC时间戳为普通时间，否则绑定的时候会有时间延迟，组件自身的bug
      this.modalForm.contract_start_date = moment(this.modalForm.contract_start_date).format('YYYY-MM-DD')
      this.modalForm.contract_end_date = moment(this.modalForm.contract_end_date).format('YYYY-MM-DD')
      this.modalForm.contract_date = moment(this.modalForm.contract_date).format('YYYY-MM-DD')
      _.forEach(this.modalForm.receivables,item => {
        item.receivable_date = moment(item.receivable_date).format('YYYY-MM-DD')
      })
    },
    addHandle() {
      this.getEmployees()
      this.getProducts()
      this.modalTitle = "新建合同"
      this.modalControl = true
    },
    modifyHandle(id) {
      this.getCompanys()
      this.getEmployees()
      this.getProducts()
      this.fileList = [{name:''}]
      this.$http.get('/fi/contracts/' + id).then((res) => {
        this.modalForm = res.data.returnValue
        _.forEach(this.modalForm.receivables,item => {
          item.count = item.count.toString()
          item.receivable_amount = item.receivable_amount.toString()
        })
        // 绑定上传的文件
        this.modalForm.oss_name ? this.fileList[0].name = this.modalForm.oss_name : this.fileList = []
        this.sum = this.modalForm.contract_amount
        this.receivableSum = this.modalForm.contract_amount
        _.forEach(this.modalForm.sales,item => {
          item.amount = item.amount.toString()
          item.totalSum = item.quantity * item.price
        })
      })
      this.modalTitle = "修改合同"
      this.modalControl = true
    },
    checkHandle(date) {
      var info = {
        category: 'contract-approval',
        businessKey:date.contract_id,
        form: {
          money:date.contract_amount,// 合同金额
          org_id:date.org_id, // 合同负责人的org_id
          customer_name:date.customer_name, // 合作公司
          responsible_name:date.responsible_name,// 合同负责人
          creator:date.creator, //合同申请人
          contract_start_date:date.contract_start_date, // 合同开始时间
          contract_end_date:date.contract_end_date, // 合同结束shijian
          sales:date.sales, // 合同的产品信息
          contract_name:date.contract_name, // 合同名称
          receivables:date.receivables, // 应收计划
          remark:date.remark, // 备注
          contract_date:date.contract_date, //合同签订时间
        }
      }
      if(date.status === '未提交')  {
        this.$flowHttp.post('/flow/create',info).then((res) => {
          this.$Message.success('审核已提交！')
          this.getContracts()
          this.modalControl = false
        }).catch(() => {
          this.$Message.error('审核提交失败，请稍后重试！')
        })
      }else if(date.status === '审核驳回') {
        date.contract_number ? info.form['contract_number'] = date.contract_number : info.form['contract_number']=''
        this.$flowHttp.post('/flow/submit',info).then((res) => {
          this.$Message.success('被驳回审核已提交！')
          this.getContracts()
          this.modalControl = false
        }).catch(() => {
          this.$Message.error('审核提交失败，请稍后重试！')
        })
      }
      
    },
    save(name) {
      this.$refs[name].validate((valid) => {
        if(valid){
          if(this.receivableSum === this.sum) {
            this.handleParmas()
            if(!this.modalForm.contract_id) {
              this.$http.post('/fi/contracts',this.modalForm).then((res) => {
                if(res.data.success) {
                  this.$Message.success('合同新建成功')
                  this.modalForm={
                    sales:[{quantity:1}],
                    receivables:[{}]
                  }
                  this.cleanDatePicker()
                  this.getContracts()
                  //this.cleanParameter()
                  this.cancel(name)
                  this.modalControl = false
                } else {
                  this.$Message.error(res.data.message)
                  this.reloading()
                }
              }).catch((res) => {
                this.$Message.error(res.message)
                this.reloading()
              })
            }else {
              this.$http.put('/fi/contracts',this.modalForm).then((res) => {
                this.$Message.success('修改成功')
                this.modalControl = false
                this.getContracts()
              }).catch((res) => {
                this.$Message.error(res.message)
                this.reloading()
              })
            }
          }else {
            this.$Message.info('总应收金额和合同金额不相等')
            this.reloading()
          }          
        }else{
          this.$Message.info('请检查所有必填选项')
          this.reloading()
        }
      })
    },
    check(name) {
      this.btnLoading = true
      var _this = this
      _this.$refs[name].validate((valid) => {
        if(valid) {
          if(this.receivableSum === this.sum) {
            this.handleParmas()
          // 新建
            if(!_this.modalForm.contract_id) {
              return new Promise((resolve,reject) => {
                _this.$http.post('/fi/contracts',_this.modalForm).then((res) => {
                  resolve(res.data.returnValue)
                }).catch((err) => {
                  _this.$Message.error(err.message)
                })
              }).then(function (contract_id) {
                return new Promise((resolve,reject) => {
                  _this.$http.get('/fi/contracts/'+ contract_id).then((res) => {
                    resolve(res.data.returnValue)
                  }).catch((err) => {
                    _this.$Message.error(err.message)
                  })
                })
              }).then(function (contractInfo) {
                var info = {
                  category: 'contract-approval',
                  businessKey:contractInfo.contract_id,
                  form: {
                    money:contractInfo.contract_amount,// 合同金额
                    org_id:contractInfo.org_id, // 合同负责人的org_id
                    customer_name:contractInfo.customer_name, // 合作公司
                    responsible_name:contractInfo.responsible_name,// 合同负责人
                    creator:contractInfo.creator, //合同申请人
                    contract_start_date:contractInfo.contract_start_date, // 合同开始时间
                    contract_end_date:contractInfo.contract_end_date, // 合同结束shijian
                    sales:contractInfo.sales, // 合同的产品信息
                    contract_name:contractInfo.contract_name, // 合同名称
                    receivables:contractInfo.receivables, // 应收计划
                    remark:contractInfo.remark, // 备注
                    contract_date:contractInfo.contract_date, //合同签订时间
                  }
                }
                _this.$flowHttp.post('/flow/create',info).then((res) => {
                  _this.$Message.success('审核已提交！')
                  _this.modalControl = false
                  _this.btnLoading = false
                  _this.getContracts()
                  _this.cleanDatePicker()
                  _this.cancel(name)
                }).catch((err) => {
                  _this.$Message.error(err.message)
                })
              })
            }else {
              _this.checkHandle(_this.modalForm)
            }
          }else {
            _this.btnLoading = false
            _this.$Message.info('总应收金额和合同金额不相等')
            _this.reloading()
          }
        }else {
          _this.btnLoading = false
          _this.$Message.info('请填写必要信息')
          _this.reloading()
        }
      })
    },
    delete(id) {
      this.$http.delete('/fi/contracts/'+ id).then((res) => {
        this.$Message.success(res.data.message)
        this.getContracts()
      }).catch(() => {
        this.$Message.error('删除失败，请重试！')
      })
    }
  },
  computed: {
    token: {
      get() {
        return this.$auth.token()
      }
    }
  },
  components: {
    deleteBtn,
    modifyBtn,
    checkBtn,
    addBtn,
    uploadBtn
  },
  mounted() {
    this.userName = this.$auth.user().name
    this.getContracts()
    this.getCompanys()
  },
  created () {
    this.indexData = indexData
  }
}
</script>

